package cn.net.autocode.platform.setting;

import cn.hutool.core.util.DesensitizedUtil;
import cn.net.autocode.core.bean.ResultT;
import cn.net.autocode.dbManager.Dao;
import cn.net.autocode.dbManager.IdWorker;
import cn.net.autocode.platform.cache.AutoCacheUtil;
import cn.net.autocode.platform.config.PlatformConfig;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/platform/platformSetting")
public class PlatformSettingCtrl {
    private final Dao dao;
    private final AutoCacheUtil autoCacheUtil;

    public PlatformSettingCtrl(Dao dao, AutoCacheUtil autoCacheUtil) {
        this.dao = dao;
        this.autoCacheUtil = autoCacheUtil;
    }

    @RequestMapping("updateAutoCodePlatform")
    public ResultT updateAutoCodePlatform(@RequestBody JSONObject param){
        dao.updateJSON(param,"autocode_platform");
        PlatformConfig.isInit = false;
        return ResultT.success();
    }

    @RequestMapping("online")
    public ResultT online(@RequestBody JSONObject param){
        String isMobile = param.getString("isMobile");
        JSONArray array = autoCacheUtil.getAllOnlineUsers(isMobile);
        return ResultT.success(array);
    }


    @RequestMapping("saveEmail")
    public ResultT saveEmail(@RequestBody JSONObject param){
        String id = param.getString("id");
        if (id == null || id.isBlank()){
            id = IdWorker.ulid();
            param.put("id", id);
            dao.createJSON(param,"sys_email");
        }else{
            String password = param.getString("password");
            if (password == null || password.isBlank()) {
                param.remove("password");
            }
            dao.updateJSON(param,"sys_email");
        }
        return this.email();
    }


    @RequestMapping("email")
    public ResultT email(){
        JSONObject json = dao.queryJSON("select * from sys_email");
        if (json != null && !json.isEmpty()) {
            String password = json.getString("password");
            if (password != null && !password.isBlank()) {
                if (password.length() >8) {
                    int tmNum = password.length()/3;
                    password = password.substring(0, tmNum)+"*".repeat(tmNum)+password.substring(tmNum*2);
                }else{
                    password = DesensitizedUtil.passport(password);
                }
            }
            json.put("password",password);
        }
        return ResultT.success(json);
    }
}
